import Mock from 'mockjs'


// get请求从config.url获取参数，post从config.body中获取参数
function param2Obj (url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"') +
    '"}'
  )
}

let List = []
const count = 200

for (let i = 0; i < count; i++) {
  List.push(
    Mock.mock({
      id: Mock.Random.guid(),
      name: Mock.Random.cname(),
      sex: Mock.Random.integer(0, 1),
      'age|18-70': 1,
      dept: Mock.Random.cname()
    })
  )
}

export default {
  /**
   * 获取列表
   */
  getStaffList: config => {
    console.log(config, 'config')
    const { name, page = 1, limit = 10 } = param2Obj(config.url)
    console.log('name:' + name, 'page:' + page, '分页大小limit:' + limit)
    const mockList = List.filter(staff => {
      if (name && staff.name.indexOf(name) && staff.dept.indexOf(name) === -1) return false
      return true
    })
    const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
    return {
      code: 20000,
      count: mockList.length,
      list: pageList
    }
  },
  /**
   * 增加员工
   */
  createStaff: config => {
    const { name, sex, age, dept } = JSON.parse(config.body)
    console.log(JSON.parse(config.body))
    List.unshift({
      id: Mock.Random.guid(),
      name: name,
      sex: sex,
      age: age,
      dept: dept
    })
    return {
      code: 20000,
      data: {
        message: '添加成功'
      }
    }
  },
  /**
   * 删除部门
   */
  deleteStaff: config => {
    const { id } = JSON.parse(config.body)
    if (!id) {
      return {
        code: -999,
        message: '参数不正确'
      }
    } else {
      List = List.filter(s => s.id !== id)
      return {
        code: 20000,
        message: '删除成功'
      }
    }
  },
  /**
   * 批量删除
   */
  batchRemove2: config => {
    let { ids } = param2Obj(config.url)
    ids = ids.split(',')
    List = List.filter(d => !ids.includes(d.id))
    return {
      code: 20000,
      data: {
        message: '批量删除成功'
      }
    }
  },
  /**
   * 修改员工
   */
  updateStaff: config => {
    const { id, name, sex, age, dept } = JSON.parse(config.body)
    const sex_num = parseInt(sex)
    List.some(s => {
      if (s.id === id) {
        s.name = name
        s.sex = sex_num
        s.age = age
        s.dept = dept
        return true
      }
    })
    return {
      code: 20000,
      data: {
        message: '编辑成功'
      }
    }
  }
}